package com.demo.webapp.jcaptcha.core.textpaster;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.text.AttributedString;

import com.octo.captcha.CaptchaException;
import com.octo.captcha.component.image.color.ColorGenerator;
import com.octo.captcha.component.image.textpaster.SimpleTextPaster;

public class ResizeTextPaster extends SimpleTextPaster {

	/**
	 * 字间距
	 */
	private int kerning = 2;
	
	/**
	 * 相对X轴偏移量（调整验证码在图片中的坐标位置）
	 */
	private int offsetX = 0;
	
	/**
	 * 相对Y轴偏移量
	 */
	private int offsetY = 0;
	
	public ResizeTextPaster(Integer minAcceptedWordLength,
			Integer maxAcceptedWordLength, Color textColor) {
		super(minAcceptedWordLength, maxAcceptedWordLength, textColor);
	}

	public ResizeTextPaster(Integer minAcceptedWordLength,
			Integer maxAcceptedWordLength, ColorGenerator colorGenerator) {
		super(minAcceptedWordLength, maxAcceptedWordLength, colorGenerator);
	}

	public ResizeTextPaster(Integer minAcceptedWordLength,
			Integer maxAcceptedWordLength, ColorGenerator colorGenerator,
			Boolean manageColorPerGlyph) {
		super(minAcceptedWordLength, maxAcceptedWordLength, colorGenerator,
				manageColorPerGlyph);
	}

	public BufferedImage pasteText(BufferedImage background,
			AttributedString attributedWord) throws CaptchaException {
		int x = background.getWidth() / 20;
		int y = background.getHeight() / 2;
		BufferedImage out = new BufferedImage(background.getWidth(),
				background.getHeight(), background.getType());
		Graphics2D g2 = getBackgroundAndSetTextColor(out, background);
		  // 消除锯齿边缘  
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
		ChangeableAttributedString newAttrString = new ChangeableAttributedString(g2, attributedWord, this.kerning);
		// 独立设置字间距
		newAttrString.useMinimumSpacing(this.kerning);
		
		// 使用偏移量offset,对验证码进行位置调整
		newAttrString.moveTo(x + getOffsetX(), y + getOffsetY());

		if (isManageColorPerGlyph())
			newAttrString.drawString(g2, getColorGenerator());
		else {
			newAttrString.drawString(g2);
		}
		g2.dispose();
		return out;
	}

	protected Graphics2D getBackgroundAndSetTextColor(BufferedImage out,
			BufferedImage background) {
		Graphics2D pie = (Graphics2D) out.getGraphics();

		pie.drawImage(background, 0, 0, out.getWidth(), out.getHeight(), null);

		pie.setColor(this.getColorGenerator().getNextColor());
		return pie;
	}

	public void setKerning(int kerning) {
		this.kerning = kerning;
	}

	public void setOffsetX(int offsetX) {
		this.offsetX = offsetX;
	}

	public void setOffsetY(int offsetY) {
		this.offsetY = offsetY;
	}

	public int getKerning() {
		return kerning;
	}

	public int getOffsetX() {
		return offsetX;
	}

	public int getOffsetY() {
		return offsetY;
	}
}
